<template>
  <div class="map-container">
    <!-- 地图容器 -->
    <div ref="mapContainer" class="map-content">
      <div v-if="loading" class="loading-overlay">
        <div class="loading"></div>
        <p class="loading-text">地图加载中...</p>
      </div>
    </div>

    <!-- 地图控制面板 -->
    <div class="map-controls">
      <div class="control-group">
        <button 
          class="control-btn"
          @click="zoomIn"
          title="放大"
        >
          <i class="icon-zoom-in"></i>
        </button>
        <button 
          class="control-btn"
          @click="zoomOut"
          title="缩小"
        >
          <i class="icon-zoom-out"></i>
        </button>
        <button 
          class="control-btn"
          @click="resetView"
          title="重置视图"
        >
          <i class="icon-reset"></i>
        </button>
      </div>
    </div>

    <!-- 图例说明 -->
    <div class="map-legend">
      <div class="legend-title">非遗项目分布</div>
      <div class="legend-scale">
        <div class="scale-item" v-for="(color, index) in legendColors" :key="index">
          <div class="color-block" :style="{ backgroundColor: color }"></div>
          <span class="scale-text">{{ getScaleText(index) }}</span>
        </div>
      </div>
    </div>

    <!-- 数据统计 -->
    <div class="map-stats">
      <div class="stat-item">
        <span class="stat-label">总项目数</span>
        <span class="stat-value">{{ totalCount }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">覆盖省份</span>
        <span class="stat-value">{{ provinceCount }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import * as echarts from 'echarts'
import 'echarts/map/js/china.js'
import { useHeritageStore } from '../stores/heritageStore'

const mapContainer = ref(null)
const loading = ref(true)
const heritageStore = useHeritageStore()
let chart = null

// 图例颜色
const legendColors = ['#e0f3fa', '#abd9e9', '#74add1', '#4575b4', '#313695']

// 统计数据
const totalCount = computed(() => {
  return heritageStore.regionData.reduce((sum, item) => sum + item.value, 0)
})

const provinceCount = computed(() => {
  return heritageStore.regionData.filter(item => item.value > 0).length
})

// 获取图例文本
const getScaleText = (index) => {
  const max = Math.max(...heritageStore.regionData.map(item => item.value))
  const step = max / 4
  return index === 0 ? '0' : 
         index === 4 ? `${Math.ceil(max)}` : 
         `${Math.ceil(step * index)}`
}

// 初始化地图
const initMap = () => {
  chart = echarts.init(mapContainer.value)
  
  const option = {
    backgroundColor: '#ffffff',
    tooltip: {
      trigger: 'item',
      formatter: params => {
        const data = heritageStore.regionData.find(item => item.name === params.name)
        const tooltipContent = [
          '<div class="map-tooltip">',
          `<h4>${params.name}</h4>`,
          `<p>非遗项目数量: ${data?.value || 0}</p>`
        ]

        if (data?.heritageList) {
          tooltipContent.push('<div class="heritage-list">')
          data.heritageList.forEach(item => {
            tooltipContent.push(
              '<div class="heritage-item">',
              `<span class="heritage-name">${item.name}</span>`,
              `<span class="heritage-category">${item.category}</span>`,
              '</div>'
            )
          })
          tooltipContent.push('</div>')
        }

        tooltipContent.push('</div>')
        return tooltipContent.join('')
      }
    },
    visualMap: {
      min: 0,
      max: Math.max(...heritageStore.regionData.map(item => item.value)),
      text: ['高', '低'],
      inRange: {
        color: legendColors
      },
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: 20
    },
    geo: {
      map: 'china',
      roam: true,
      zoom: 1.2,
      center: [105, 36],
      label: {
        show: true,
        fontSize: 8,
        color: '#333'
      },
      itemStyle: {
        areaColor: '#f3f3f3',
        borderColor: '#999',
        borderWidth: 0.5
      },
      emphasis: {
        label: {
          show: true,
          color: '#fff'
        },
        itemStyle: {
          areaColor: '#4575b4'
        }
      }
    },
    series: [{
      name: '非遗分布',
      type: 'map',
      map: 'china',
      roam: true,
      zoom: 1.2,
      center: [105, 36],
      data: heritageStore.regionData,
      emphasis: {
        label: {
          show: true,
          color: '#fff'
        },
        itemStyle: {
          areaColor: '#4575b4'
        }
      }
    }]
  }

  chart.setOption(option)
  loading.value = false

  // 添加点击事件
  chart.on('click', params => {
    if (params.data) {
      heritageStore.setSelectedRegion(params.name)
    }
  })
}

// 地图控制方法
const zoomIn = () => {
  const option = chart.getOption()
  const zoom = option.series[0].zoom || 1
  chart.setOption({
    series: [{
      zoom: Math.min(zoom * 1.2, 5)
    }]
  })
}

const zoomOut = () => {
  const option = chart.getOption()
  const zoom = option.series[0].zoom || 1
  chart.setOption({
    series: [{
      zoom: Math.max(zoom / 1.2, 0.5)
    }]
  })
}

const resetView = () => {
  chart.setOption({
    series: [{
      zoom: 1.2,
      center: [105, 36]
    }]
  })
}

// 生命周期钩子
onMounted(async () => {
  await heritageStore.fetchHeritageData()
  initMap()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
  }
  window.removeEventListener('resize', handleResize)
})

// 处理窗口大小变化
const handleResize = () => {
  chart?.resize()
}
</script>

<style scoped>
.map-container {
  @apply relative w-full h-[600px] bg-white rounded-lg shadow-lg overflow-hidden;
}

.map-content {
  @apply w-full h-full;
}

.loading-overlay {
  @apply absolute inset-0 flex flex-col items-center justify-center bg-white bg-opacity-80;
}

.loading-text {
  @apply mt-4 text-gray-600;
}

.map-controls {
  @apply absolute top-4 right-4 z-10;
}

.control-group {
  @apply flex flex-col gap-2;
}

.control-btn {
  @apply w-10 h-10 rounded-full bg-white shadow-md flex items-center justify-center
         hover:bg-gray-50 transition-colors duration-200;
}

.map-legend {
  @apply absolute bottom-4 left-4 bg-white p-3 rounded-lg shadow-md;
}

.legend-title {
  @apply text-sm font-medium text-gray-700 mb-2;
}

.legend-scale {
  @apply flex items-center gap-2;
}

.scale-item {
  @apply flex items-center gap-1;
}

.color-block {
  @apply w-4 h-4 rounded-sm;
}

.scale-text {
  @apply text-xs text-gray-600;
}

.map-stats {
  @apply absolute top-4 left-4 flex gap-4;
}

.stat-item {
  @apply bg-white px-4 py-2 rounded-lg shadow-md;
}

.stat-label {
  @apply text-sm text-gray-600;
}

.stat-value {
  @apply block text-xl font-bold text-blue-600;
}

/* 自定义提示框样式 */
:deep(.map-tooltip) {
  @apply p-2;
}

:deep(.map-tooltip h4) {
  @apply text-base font-bold mb-1;
}

:deep(.heritage-list) {
  @apply mt-2 max-h-32 overflow-y-auto;
}

:deep(.heritage-item) {
  @apply flex justify-between items-center text-sm py-1;
}

:deep(.heritage-name) {
  @apply text-gray-800;
}

:deep(.heritage-category) {
  @apply text-gray-500 text-xs;
}

/* 图标样式 */
.icon-zoom-in,
.icon-zoom-out,
.icon-reset {
  @apply w-5 h-5 text-gray-600;
}
</style>